<?php
/**
 * @author      Alex Bilbie <hello@alexbilbie.com>
 * @copyright   Copyright (c) Alex Bilbie
 * @license     http://mit-license.org/
 *
 * @link        https://github.com/thephpleague/oauth2-server
 */

namespace app\components\oauth2\repositories;

use app\helpers\Redis;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use app\components\oauth2\entities\RefreshTokenEntity;

class RefreshTokenRepository implements RefreshTokenRepositoryInterface
{
    const PREFIX = 'refresh_token:';
    /**
     * {@inheritdoc}
     */
    public function persistNewRefreshToken(RefreshTokenEntityInterface $refreshTokenEntity)
    {
        $redis = Redis::getRedis();
        $tokenId = $refreshTokenEntity->getIdentifier();
        $expiryDateTime = $refreshTokenEntity->getExpiryDateTime()->getTimestamp();
        $seconds = $expiryDateTime - \time();
        $redis->set(self::PREFIX.$tokenId,(string)$refreshTokenEntity->getAccessToken(),['EX'=>$seconds]);
    }

    /**
     * {@inheritdoc}
     */
    public function revokeRefreshToken($tokenId)
    {
        $redis = Redis::getRedis();
        $redis->del(self::PREFIX.$tokenId);
        // Some logic to revoke the refresh token in a database
    }

    /**
     * {@inheritdoc}
     */
    public function isRefreshTokenRevoked($tokenId)
    {
        $redis = Redis::getRedis();
        return !$redis->exists(self::PREFIX.$tokenId); // Access token hasn't been revoked
    }

    /**
     * {@inheritdoc}
     */
    public function getNewRefreshToken()
    {
        return new RefreshTokenEntity();
    }
}
